package com.have.blog.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.have.blog.admin.constant.AdminBlogConstant;
import com.have.blog.admin.constant.AdminMessageConstant;
import com.have.blog.admin.domain.dto.UserDto;
import com.have.blog.admin.service.BlogUserService;
import com.have.blog.admin.service.SystemParamService;
import com.have.blog.base.enums.BlogStatus;
import com.have.blog.base.wrapper.Wrapper;
import com.have.blog.model.mapper.UserMapper;
import com.have.blog.model.models.User;
import com.have.blog.model.models.UserExample;
import com.have.blog.picture.service.PictureFeignApi;
import com.have.blog.utils.MD5Utils;
import com.have.blog.utils.MyBeanUtils;
import com.have.blog.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
@SuppressWarnings("all")
public class BlogUserServiceImpl implements BlogUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PictureFeignApi pictureFeignApi;
    @Autowired
    private SystemParamService systemParamService;

    @Override
    public List<UserDto> getList(UserDto userDto) {
        PageHelper.startPage(userDto.getPageNum(), userDto.getPageSize());
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andStatusEqualTo(BlogStatus.ENABLE.getStatus());
        if (StringUtils.isNotEmpty(userDto.getKeyword()) && StringUtils.isNotEmpty(userDto.getKeyword().trim())) {
            criteria.andNicknameLike("%" + userDto.getKeyword() + "%");
        }
        if (StringUtils.isNotEmpty(userDto.getSource()) && StringUtils.isNotEmpty(userDto.getSource().trim())) {
            criteria.andSourceEqualTo(userDto.getSource());
        }
        if (userDto.getCommentStatus() != null) {
            criteria.andCommentStatusEqualTo(userDto.getCommentStatus());
        }
        if(StringUtils.isNotEmpty(userDto.getOrderByAscColumn())) {
            // 将驼峰转换成下划线
            String column = StringUtils.underLine(new StringBuffer(userDto.getOrderByAscColumn())).toString();
            example.setOrderByClause(column + " asc");
        } else if(StringUtils.isNotEmpty(userDto.getOrderByDescColumn())) {
            // 将驼峰转换成下划线
            String column = StringUtils.underLine(new StringBuffer(userDto.getOrderByDescColumn())).toString();
            example.setOrderByClause(column + " desc");
        } else {
            example.setOrderByClause("create_time desc");
        }
        List<User> userList = userMapper.selectByExample(example);
        List<UserDto> resultList = MyBeanUtils.copyListProperties(userList, UserDto::new);

        // 获取用户头像
        List<Integer> picUids = new ArrayList<>();
        resultList.forEach(item ->{
            if (item.getHeadUid() != null) {
                picUids.add(item.getHeadUid());
            }
        });

        if (!CollectionUtils.isEmpty(picUids)) {
            Wrapper<Map<Integer, String>> picWrapper = pictureFeignApi.getPicturesUrl(picUids);
            if (picWrapper.isSuccess()) {
                Map<Integer, String> picMap = picWrapper.getData();
                for (UserDto dto : resultList) {
                    dto.setPhotoUrl(picMap.get(dto.getHeadUid()));
                }
            }
        }

        return resultList;
    }

    @Override
    public Wrapper addUser(UserDto userDto) {
        User user = new User();
        MyBeanUtils.copyProperties(userDto, user, AdminBlogConstant.STATUS);
        String defaultPassword = systemParamService.getSystemParamValueByKey(AdminBlogConstant.SYS_DEFAULT_PASSWORD);
        user.setPassword(MD5Utils.string2MD5(defaultPassword));
        user.setSource("YUEQIAN");
        user.setStartEmailNotification(0);
        user.setStatus(BlogStatus.ENABLE.getStatus());
        int result = userMapper.insert(user);
        if (result > 0) {
            return Wrapper.successWithMessage(AdminMessageConstant.INSERT_SUCCESS);
        }
        return Wrapper.failed(AdminMessageConstant.INSERT_FAIL);
    }

    @Override
    public Wrapper editUser(UserDto userDto) {
        User user = userMapper.selectByPrimaryKey(userDto.getUid());
        user.setUsername(userDto.getUsername());
        user.setEmail(userDto.getEmail());
        user.setStartEmailNotification(userDto.getStartEmailNotification());
        user.setOccupation(userDto.getOccupation());
        user.setGender(userDto.getGender());
        user.setQqNumber(userDto.getQqNumber());
        user.setSummary(userDto.getSummary());
        user.setBirthday(userDto.getBirthday());
        user.setNickname(userDto.getNickname());
        user.setHeadUid(userDto.getHeadUid());
        user.setUserTag(userDto.getUserTag());
        user.setStatus(userDto.getStatus());
        user.setCommentStatus(userDto.getCommentStatus());
        int result = userMapper.updateByPrimaryKeySelective(user);
        if (result > 0) {
            return Wrapper.successWithMessage(AdminMessageConstant.UPDATE_SUCCESS);
        }
        return Wrapper.failed(AdminMessageConstant.UPDATE_FAIL);
    }

    @Override
    public Wrapper deleteUser(UserDto userDto) {
        User user = userMapper.selectByPrimaryKey(userDto.getUid());
        user.setStatus(BlogStatus.DISABLE.getStatus());
        int result = userMapper.updateByPrimaryKeySelective(user);
        if (result > 0) {
            return Wrapper.successWithMessage(AdminMessageConstant.DELETE_SUCCESS);
        }
        return Wrapper.failed(AdminMessageConstant.DELETE_FAIL);
    }

    @Override
    public Wrapper resetUserPassword(UserDto userDto) {
        String defaultPassword = systemParamService.getSystemParamValueByKey(AdminBlogConstant.SYS_DEFAULT_PASSWORD);
        User user = userMapper.selectByPrimaryKey(userDto.getUid());
        user.setPassword(MD5Utils.string2MD5(defaultPassword));
        int result = userMapper.updateByPrimaryKeySelective(user);
        if (result > 0) {
            return Wrapper.success();
        }
        return Wrapper.failed();
    }
}
